package com.zzyl.nursing.service.impl;

import java.util.*;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.time.ZoneOffset;
import java.util.stream.Collectors;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.ShowProductRequest;
import com.huaweicloud.sdk.iotda.v5.model.ShowProductResponse;
import com.huaweicloud.sdk.iotda.v5.model.ServiceCapability;
import com.huaweicloud.sdk.iotda.v5.model.ServiceProperty;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.FamilyMemberElderDto;
import com.zzyl.nursing.dto.QueryDeviceDataListDto;
import com.zzyl.nursing.dto.QueryDeviceDto;
import com.zzyl.nursing.dto.UserLoginRequestDto;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.mapper.FamilyMemberElderMapper;
import com.zzyl.nursing.service.WechatService;
import com.zzyl.nursing.vo.FamilyMemberElderVo;
import com.zzyl.nursing.vo.LoginVo;
import com.zzyl.nursing.vo.QueryDeviceDataListVo;
import com.zzyl.nursing.vo.QueryDeviceVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.FamilyMemberMapper;
import com.zzyl.nursing.domain.FamilyMember;
import com.zzyl.nursing.service.IFamilyMemberService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 老人家属Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-09-19
 */
@Service
@Slf4j
public class FamilyMemberServiceImpl extends ServiceImpl<FamilyMemberMapper,FamilyMember> implements IFamilyMemberService
{
    @Autowired
    private FamilyMemberMapper familyMemberMapper;

    @Autowired
    private WechatService wechatService;

    @Autowired
    private TokenService tokenService;
    @Autowired
    private ElderServiceImpl elderService;
    @Autowired
    private FamilyMemberElderMapper familyMemberElderMapper;
    @Autowired
    private DeviceServiceImpl deviceService;

    @Autowired
    private IoTDAClient client;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    
    @Autowired
    private DeviceDataMapper deviceDataMapper;

    static List<String> DEFAULT_NICK_NAME = ListUtil.of(
            "生活更美好",
            "大桔大利",
            "日富一日",
            "好柿开花",
            "柿柿如意",
            "一椰暴富",
            "大柚所为",
            "杨梅吐气",
            "天生荔枝");

    /**
     * 小程序登录
     *
     * @param dto 登录参数
     * @return 登录信息
     */
    @Override
    public LoginVo login(UserLoginRequestDto dto) {

        //1.获取openid(调用微信的接口获取) ***
        String openid = wechatService.getOpenid(dto.getCode());

        //2.根据openid查询用户
        LambdaQueryWrapper<FamilyMember> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FamilyMember::getOpenId,openid);
        FamilyMember familyMember = getOne(queryWrapper);

        //3.判断用户是否存在，用户不存在，就构建用户
        if(ObjectUtil.isEmpty(familyMember)){
            /*familyMember = new FamilyMember();
            familyMember.setOpenId(openid);*/
            familyMember = FamilyMember.builder()
                    .openId(openid)
                    .build();
        }

        //4.获取用户的手机号（调用微信的接口获取）***
        String phone = wechatService.getPhone(dto.getPhoneCode());

        //5. 新增或修改用户
        inserOrUpdateFamilyMember(familyMember,phone);

        //6. 把用户的信息封装到token,返回
        Map<String,Object> claims = new HashMap<>();
        claims.put("username",familyMember.getName());
        claims.put("userId",familyMember.getId());
        String token = tokenService.createToken(claims);

        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);
        loginVo.setNickName(familyMember.getName());

        return loginVo;
    }

    /**
     * 新增家人
     * @param dto,token 参数
     * @return 1成功，0失败
     */
    @Override
    public int add(FamilyMemberElderDto dto, String token) {
        // 从token中获取用户信息
        Map<String, Object> claims = tokenService.parseToken(token);
        // 使用Number类型统一处理
        Long currentUserId = ((Number) claims.get("userId")).longValue();

        Elder elder = elderService.lambdaQuery()
                .eq(Elder::getIdCardNo, dto.getIdCard())
                .eq(Elder::getName, dto.getName())
                .one();
        if(ObjectUtil.isEmpty(elder)){
            throw new RuntimeException("没有该老人");
        }

        Long elderId = elder.getId();
        
        // 检查是否已经绑定过该老人
        FamilyMemberElder existingRelation = familyMemberElderMapper.selectOne(
                new LambdaQueryWrapper<FamilyMemberElder>()
                        .eq(FamilyMemberElder::getFamilyMemberId, currentUserId)
                        .eq(FamilyMemberElder::getElderId, elderId)
        );
        
        if (ObjectUtil.isNotEmpty(existingRelation)) {
            throw new RuntimeException("您已经绑定过该老人，无需重复绑定");
        }

        FamilyMemberElder familyMemberElder = new FamilyMemberElder();
        familyMemberElder.setCreateTime(new Date());
        familyMemberElder.setUpdateTime(new Date());
        familyMemberElder.setCreateBy(currentUserId.toString());
        familyMemberElder.setFamilyMemberId(currentUserId);
        familyMemberElder.setElderId(elderId);
        familyMemberElder.setRemark(dto.getRemark());
        return familyMemberElderMapper.insertFamilyMemberElder(familyMemberElder);

    }

    /**
     * 获取家人列表
     * @param token 令牌
     * @return 家人列表
     */
    @Override
    public List<FamilyMemberElder> selectFamilyMember(String token) {
        // 从token中获取用户信息
        Map<String, Object> claims = tokenService.parseToken(token);
        // 使用Number类型统一处理
        Long currentUserId = ((Number) claims.get("userId")).longValue();
        // 从中间表查到老人Id，再去对应老人表查到老人姓名
        List<FamilyMemberElder> familyMemberElderList = familyMemberElderMapper.selectList(
                new LambdaQueryWrapper<FamilyMemberElder>()
                .eq(FamilyMemberElder::getFamilyMemberId,currentUserId)
        );
        
        if (!familyMemberElderList.isEmpty()) {
            // 收集所有老人ID
            List<Long> elderIds = familyMemberElderList.stream()
                .map(FamilyMemberElder::getElderId)
                .collect(Collectors.toList());
            
            // 批量查询老人信息
            Map<Long, Elder> elderMap = elderService.listByIds(elderIds).stream()
                .collect(Collectors.toMap(Elder::getId, elder -> elder));
            
            // 设置老人姓名
            familyMemberElderList.forEach(familyMemberElder -> {
                Elder elder = elderMap.get(familyMemberElder.getElderId());
                if (elder != null) {
                    familyMemberElder.setElderName(elder.getName());
                }
            });
        }

        return familyMemberElderList;
    }

    /**
     * 分页查询家人列表
     * @param pageNum 页码
     * @param pageSize 每页数量
     * @param token 令牌
     * @return 家人列表
     */
    @Override
    public List<FamilyMemberElderVo> pageList(int pageNum, int pageSize, String token) {
        // 从token中获取用户信息
        Map<String, Object> claims = tokenService.parseToken(token);
        // 使用Number类型统一处理
        Long currentUserId = ((Number) claims.get("userId")).longValue();

        // 使用PageHelper进行分页
        PageHelper.startPage(pageNum, pageSize);

        // 调用已有的mapper方法
        List<FamilyMemberElderVo> result = familyMemberElderMapper.selectByFamilyMemberElderId(currentUserId);

        return result;
    }

    /**
     * 查询设备属性状态
     * @param dto 查询设备属性状态的参数
     * @param token 令牌
     * @return 设备属性状态
     */
    @Override
    public QueryDeviceVo queryDevicePropertyStatus(QueryDeviceDto dto, String token) {
        //先查看是否有该设备
        Device device = deviceService.lambdaQuery()
                .eq(Device::getProductKey, dto.getProductKey())
                .eq(Device::getDeviceName, dto.getDeviceName())
                .one();
        if(ObjectUtil.isEmpty(device)){
            throw new RuntimeException("没有该设备");
        }
        
        //构建返回对象
        QueryDeviceVo queryDeviceVo = new QueryDeviceVo();
        DeviceDataList dataList = new DeviceDataList();
        List<QueryDevicePropertyStatus> propertyStatusInfoList = new ArrayList<>();
        
        //从华为云获取产品信息和属性定义
        ShowProductRequest request = new ShowProductRequest();
        request.withProductId(device.getProductKey());
        ShowProductResponse response = client.showProduct(request);
        
        //获取产品的服务能力和属性定义
        List<ServiceProperty> properties = new ArrayList<>();
        if (response != null && response.getServiceCapabilities() != null) {
            for (ServiceCapability service : response.getServiceCapabilities()) {
                if (service.getProperties() != null) {
                    properties.addAll(service.getProperties());
                }
            }
        }
        
        //创建属性ID到属性定义的映射
        Map<String, ServiceProperty> propertyMap = new HashMap<>();
        for (ServiceProperty property : properties) {
            propertyMap.put(property.getPropertyName(), property);
        }
        
        //从Redis缓存中获取设备数据
        String deviceDataJson = (String) redisTemplate.opsForHash().get(CacheConstants.IOT_DEVICE_LAST_DATA, device.getIotId());
        if (!ObjectUtil.isEmpty(deviceDataJson)) {
            //解析设备数据
            List<DeviceData> deviceDataList = JSONUtil.toList(deviceDataJson, DeviceData.class);
            if (!ObjectUtil.isEmpty(deviceDataList)) {
                //遍历设备数据，转换为前端需要的格式
                for (DeviceData deviceData : deviceDataList) {
                    QueryDevicePropertyStatus propertyStatus = new QueryDevicePropertyStatus();
                    String functionId = deviceData.getFunctionId();
                    
                    //从华为云获取的属性定义中设置数据类型和名称
                    ServiceProperty property = propertyMap.get(functionId);
                    if (property != null) {
                        propertyStatus.setDataType(property.getDataType());
                        propertyStatus.setIdentifier(functionId);
                        propertyStatus.setName(property.getPropertyName());
                        propertyStatus.setUnit(property.getUnit() != null ? property.getUnit() : "");
                        
                        //设置时间和值
                        propertyStatus.setTime(String.valueOf(deviceData.getAlarmTime().toInstant(ZoneOffset.of("+8")).toEpochMilli()));
                        propertyStatus.setValue(deviceData.getDataValue());
                        
                        propertyStatusInfoList.add(propertyStatus);
                    }
                }
            }
        }
        
        dataList.setPropertyStatusInfo(propertyStatusInfoList);
        queryDeviceVo.setList(dataList);
        
        return queryDeviceVo;
    }

    /**
     * 查询设备数据列表-按天
     * @param dto 查询设备数据列表的参数
     * @return 设备数据列表
     */
    @Override
    public List<QueryDeviceDataListVo> queryDeviceDataListByDay(QueryDeviceDataListDto dto) {
        // 验证参数
        if (ObjectUtil.isEmpty(dto.getIotId()) || ObjectUtil.isEmpty(dto.getFunctionId())
                || ObjectUtil.isEmpty(dto.getStartTime()) || ObjectUtil.isEmpty(dto.getEndTime())) {
            throw new RuntimeException("参数不能为空");
        }

        // 转换时间戳为LocalDateTime
        LocalDateTime startDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(dto.getStartTime()), ZoneId.systemDefault());
        LocalDateTime endDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(dto.getEndTime()), ZoneId.systemDefault());

        // 查询设备数据
        List<DeviceData> deviceDataList = deviceDataMapper.selectList(
                new LambdaQueryWrapper<DeviceData>()
                        .eq(DeviceData::getIotId, dto.getIotId())
                        .eq(DeviceData::getFunctionId, dto.getFunctionId())
                        .between(DeviceData::getAlarmTime, startDateTime, endDateTime)
                        .orderByDesc(DeviceData::getAlarmTime) // 按时间倒序排列，便于取最新
        );

        // 按小时分组，保留每小时最新的数据
        Map<String, DeviceData> latestHourlyData = new HashMap<>();
        for (DeviceData data : deviceDataList) {
            String hourKey = String.format("%02d:00", data.getAlarmTime().getHour());
            if (!latestHourlyData.containsKey(hourKey)) {
                latestHourlyData.put(hourKey, data);
            }
        }

        // 构建返回结果
        List<QueryDeviceDataListVo> result = new ArrayList<>();
        for (int hour = 0; hour < 24; hour++) {
            String hourStr = String.format("%02d:00", hour);
            DeviceData latestData = latestHourlyData.get(hourStr);

            QueryDeviceDataListVo vo = new QueryDeviceDataListVo();
            vo.setDateTime(hourStr);
            if (latestData != null) {
                vo.setDataValue(latestData.getDataValue());
            } else {
                vo.setDataValue("0");
            }
            result.add(vo);
        }

        return result;
    }

    /**
     * 查询设备数据列表（按周）
     *
     * @param dto 查询参数
     * @return 设备数据列表
     */
    @Override
    public List<QueryDeviceDataListVo> queryDeviceDataListByWeek(QueryDeviceDataListDto dto) {
        // 验证参数
        if (ObjectUtil.isEmpty(dto.getIotId()) || ObjectUtil.isEmpty(dto.getFunctionId())
                || ObjectUtil.isEmpty(dto.getStartTime()) || ObjectUtil.isEmpty(dto.getEndTime())) {
            throw new RuntimeException("参数不能为空");
        }

        // 转换时间戳为LocalDateTime
        LocalDateTime startDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(dto.getStartTime()), ZoneId.systemDefault());
        LocalDateTime endDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(dto.getEndTime()), ZoneId.systemDefault());

        // 确保时间范围不超过7天
        if (ChronoUnit.DAYS.between(startDateTime.toLocalDate(), endDateTime.toLocalDate()) > 7) {
            endDateTime = startDateTime.plusDays(6).withHour(23).withMinute(59).withSecond(59);
        }

        // 查询设备数据
        List<DeviceData> deviceDataList = deviceDataMapper.selectList(
                new LambdaQueryWrapper<DeviceData>()
                        .eq(DeviceData::getIotId, dto.getIotId())
                        .eq(DeviceData::getFunctionId, dto.getFunctionId())
                        .between(DeviceData::getAlarmTime, startDateTime, endDateTime)
                        .orderByDesc(DeviceData::getAlarmTime)
        );

        // 按日期分组，保留每天最新的数据
        Map<LocalDate, DeviceData> latestDailyData = new HashMap<>();
        for (DeviceData data : deviceDataList) {
            LocalDate date = data.getAlarmTime().toLocalDate();
            if (!latestDailyData.containsKey(date)) {
                latestDailyData.put(date, data);
            }
        }

        // 构建返回结果
        List<QueryDeviceDataListVo> result = new ArrayList<>();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM.dd");
        LocalDate currentDate = startDateTime.toLocalDate();

        while (!currentDate.isAfter(endDateTime.toLocalDate())) {
            DeviceData latestData = latestDailyData.get(currentDate);

            QueryDeviceDataListVo vo = new QueryDeviceDataListVo();
            vo.setDateTime(currentDate.format(formatter));
            if (latestData != null) {
                vo.setDataValue(latestData.getDataValue());
            } else {
                vo.setDataValue("0");
            }
            result.add(vo);

            currentDate = currentDate.plusDays(1);
        }

        return result;
    }

    /**
     * 新增或修改用户
     * @param familyMember
     * @param phone
     */
    private void inserOrUpdateFamilyMember(FamilyMember familyMember, String phone) {

        //1. 判断新的手机跟数据库中保存的手机号是否一致
        if(ObjectUtil.notEqual(familyMember.getPhone(),phone)){
            familyMember.setPhone(phone);
        }

        //2. id是否存在，如存在，就修改
        if(ObjectUtil.isNotEmpty(familyMember.getId())){
            updateById(familyMember);
            return;
        }

        //3. 不存在，就新增 (拼装用户的昵称：随机字符串+手机号后4位)
        int index = (int)(Math.random() * DEFAULT_NICK_NAME.size());
        String nickName = DEFAULT_NICK_NAME.get(index)+ phone.substring(phone.length()-4);
        familyMember.setName(nickName);
        save(familyMember);

    }

    /**
     * 查询老人家属
     * 
     * @param id 老人家属主键
     * @return 老人家属
     */
    @Override
    public FamilyMember selectFamilyMemberById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询老人家属列表
     * 
     * @param familyMember 老人家属
     * @return 老人家属
     */
    @Override
    public List<FamilyMember> selectFamilyMemberList(FamilyMember familyMember)
    {
        return familyMemberMapper.selectFamilyMemberList(familyMember);
    }

    /**
     * 新增老人家属
     * 
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int insertFamilyMember(FamilyMember familyMember)
    {
        return save(familyMember)?1:0;
    }

    /**
     * 修改老人家属
     * 
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int updateFamilyMember(FamilyMember familyMember)
    {
        return updateById(familyMember)?1:0;
    }

    /**
     * 批量删除老人家属
     * 
     * @param ids 需要删除的老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids))?1:0;
    }

    /**
     * 删除老人家属信息
     * 
     * @param id 老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberById(Long id)
    {
        return removeById(id)?1:0;
    }

}
